﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using SF.Base.Core;
using System.Data;
using System.Text;
using Nii.JSON;
using System.Text.RegularExpressions;
using Newtonsoft.Json;
using System.Collections;

namespace SF.Dict.Web {
	public partial class Voc : BasePage {
		protected string OpenError = string.Empty;
		protected string AuthorizeKey = string.Empty;

		#region 全局变量

		protected long Vid {
			get {
				return ViewState["Vid"] == null ? -1 : long.Parse(ViewState["Vid"].ToString());
			}
			set {
				ViewState["Vid"] = value;
			}
		}

		protected int KnowCount {
			get;
			set;
		}
		protected int NKnowCount {
			get;
			set;
		}

		protected Boolean IsFollow {
			get;
			set;
		}

		protected string VocabularyId {
			get {
				return ViewState["VocabularyId"] == null ? "" : ViewState["VocabularyId"].ToString();
			}
			set {
				ViewState["VocabularyId"] = value;
			}
		}

		protected string Initial {
			get {
				return ViewState["Initial"] == null ? "" : ViewState["Initial"].ToString();
			}
			set {
				ViewState["Initial"] = value;
			}
		}

		#endregion

		protected void Page_Load(object sender, EventArgs e) {

			//词汇表ID
			Vid = Request.GetInt("vid", -1);
			//单词首字母 默认为A
			Initial = Request.GetStr("index");
			//用户ID

			VocabularyEntity voc = VocabularyRules.GetVocabulary(Vid);
			if (voc == null) {
				//词汇表不存在 自动跳转到词汇表选择页面
				Response.Redirect("/list.aspx");
			}

			if (Global.DTUser == null) {
				if (voc.UserId == Guid.Empty.ToString()) {
					Response.Redirect("/login.aspx?return=" + Server.UrlEncode(string.Format("/voc.aspx?vid={0}&index={1}", Vid, Initial)));
				}
				else {
					Response.Redirect("/login.aspx?return=" + Server.UrlEncode(string.Format("/voc.aspx?vid={0}", Vid)));
				}
			}

			if (Vid == -1) {
				//自动跳转到词汇表选择页面
				Response.Redirect("/list.aspx");
			}
			VocabularyId = voc.VocabularyId;

			//判断用户是否关注了本词汇表
			IsFollow = VocabularyRules.IsFollow(UserId, VocabularyId);

			if (IsFollow == false) {
				//未关注
				//int ret = DBDict.FollowVocabulary(UserId, VocabularyId);
			}
			//已关注
			pl_dictlist.Visible = true;
			ucVocAside1.VocabularyId = VocabularyId;

			//创建单词列表JSON
			//获取本词汇表全部的单词列表
			List<DictEntity> dictList = new List<DictEntity>();
			List<DictEntity> GuessDictList = new List<DictEntity>();

			if (voc.UserId == Guid.Empty.ToString()) {
				if (string.IsNullOrEmpty(Initial)) {
					Initial = "A";
				}
				dictList = DictRules.GetDictsByVid(VocabularyId, Initial);
			}
			else {
				dictList = DictRules.GetDictsByVid(VocabularyId);
				ucAbcd1.Visible = false;
			}

			dictList = BuildVocabularyJsonLists(dictList);

			//如果有效的单词少于10个，查询10个其它单词
			if (dictList.Count <= 10) {
				GuessDictList = dictList;
				GuessDictList.AddRange(DictRules.GetGuessDictsByVid(VocabularyId, Initial));
			}
			else{
				GuessDictList = dictList;
			}

			BuildGuessJson(GuessDictList);

			//查询用户单词已认识列表
			string[] know = DictRules.GetUserKnowDict(UserId, VocabularyId, Initial);

			ArrayList al = new ArrayList();

			for (int i = 0; i < know.Length; i++) {
				if (dictList.Exists(delegate(DictEntity t) { return t.DictId == know[i]; })) {
					al.Add(DictRules.GetNumId(know[i]));
				}
			}

			NKnowCount = al.Count;
			KnowCount = dictList.Count - al.Count;

			if (!ClientScript.IsClientScriptBlockRegistered("Aknow")) {
				ClientScript.RegisterClientScriptBlock(Page.GetType(), "Aknow", string.Format("var Aknow = {0} ;", JsonConvert.SerializeObject(al)), true);
			}

			//查询用户单词收藏列表
			string[] collection = DictRules.GetUserCollectDict(UserId);

			long[] collection2 = new long[collection.Length];

			for (int i = 0; i < collection.Length; i++) {
				collection2[i] = DictRules.GetNumId(collection[i]);
			}

			if (!ClientScript.IsClientScriptBlockRegistered("ACollect")) {
				ClientScript.RegisterClientScriptBlock(Page.GetType(), "ACollect", string.Format("var ACollect = {0} ;", JsonConvert.SerializeObject(collection2)), true);
			}

			//登录用户是不是创建者
			Boolean IsAdmin = (voc.UserId == UserId) ? true : false;

			if (IsAdmin) {
				hl_edit.Visible = true;
				hl_edit.NavigateUrl = "/edit.aspx?vid=" + Vid;
			}

			UserEntity CreateUser = UserRules.GetUserByUserId(voc.UserId);

			if (!ClientScript.IsClientScriptBlockRegistered("Vid")) {
				ClientScript.RegisterClientScriptBlock(Page.GetType(), "Vid", "var oVoc = {vid:" + Vid + ",status:" + voc.Status + ",adminid:" + CreateUser.UID + ",adminname:'" + CreateUser.NiceName + "',isadmin:" + IsAdmin.ToString().ToLower() + ",isfollow:" + IsFollow.ToString().ToLower() + "};", true);
			}

			ucAbcd1.VocabularyId = VocabularyId;
			ucAbcd1.Initial = Initial;

			ucVocHeader1.VocabularyId = VocabularyId;
			ucVocHeader1.Initial = Initial;
			ucVocHeader1.PageName = "voc";

			ll_title.Text = voc.Name + " | 挚友云海 | 收获于学习之外";
			DataBind();
		}

		public void BuildGuessJson(List<DictEntity> dictList) {
			JSONObject Json = new JSONObject();
			JSONArray Dicts = new JSONArray();

			foreach (DictEntity dict in dictList) {

				JSONObject Dict = new JSONObject();

				long DID = dict.Did;
				string Spell = dict.ASpell;
				string Pronunciation = dict.APronunciation.Replace("<SUP>", "(").Replace("</SUP>", ")");
				string Paraphrase = dict.Paraphrase;
				string ListIndex = dict.Initial;
				Regex Pattern = new Regex("\\[def\\](?<Par>(.|\\n|\\r)*?)\\[\\/def\\]", RegexOptions.IgnoreCase);
				MatchCollection mcParaphrase = Pattern.Matches(Paraphrase);

				if (mcParaphrase.Count > 0) {
					Paraphrase = mcParaphrase[0].Groups["Par"].Value;
				}

				Dict.put("id", DID);
				Dict.put("spell", Spell);
				Dict.put("pron", Pronunciation);
				Dict.put("ph", Paraphrase);
				Dicts.put(Dict);
			}

			Json.put("dicts", Dicts);

			if (ClientScript.IsClientScriptBlockRegistered("Guess") == false) {
				ClientScript.RegisterClientScriptBlock(Page.GetType(), "Guess", "\r\nvar GuessData; $(document).ready(function() {GuessData = " + Json.ToString() + ";});\r\n", true);
			}
		}

		/// <summary>
		/// 创建单词列表JSON
		/// </summary>
		public List<DictEntity> BuildVocabularyJsonLists(List<DictEntity> dictList) {
			JSONObject Json = new JSONObject();
			JSONArray Dicts = new JSONArray();

			List<DictEntity> DictList = new List<DictEntity>();

			int NotEditCount = 0;
			int Count = 0;
			foreach (DictEntity dict in dictList) {
				
				//被删除了
				if (dict.IsDelete == 1) {
					continue;
				}

				//未完成编辑
				if (string.IsNullOrEmpty(dict.Paraphrase)) {
					NotEditCount = NotEditCount + 1;
					continue;
				}

				JSONObject Dict = new JSONObject();

				long DID = dict.Did;
				string Spell = dict.ASpell;
				string Pronunciation = dict.APronunciation.Replace("<SUP>", "(").Replace("</SUP>", ")");
				string Paraphrase = dict.Paraphrase;
				string ListIndex = dict.Initial;
				Regex Pattern = new Regex("\\[def\\](?<Par>(.|\\n|\\r)*?)\\[\\/def\\]", RegexOptions.IgnoreCase);
				MatchCollection mcParaphrase = Pattern.Matches(Paraphrase);

				if (mcParaphrase.Count > 0) {
					Paraphrase = mcParaphrase[0].Groups["Par"].Value;
				}

				Dict.put("id", DID);
				Dict.put("spell", Spell);
				Dict.put("pron", Pronunciation);
				Dict.put("ph", Paraphrase);
				Dict.put("ph1", dict.Paraphrase);
				Dict.put("li", ListIndex);
				Dicts.put(Dict);
				Count ++;
				DictList.Add(dict);
			}
			Json.put("dicts", Dicts);
			Json.put("vid", Vid);
			Json.put("notedit", NotEditCount);

			dictcount.Text = Count.ToString();

			if (ClientScript.IsClientScriptBlockRegistered("BuildList") == false) {
				ClientScript.RegisterClientScriptBlock(Page.GetType(), "BuildList", "var jsondata; $(document).ready(function() {jsondata = " + Json.ToString() + ";BuildList();});", true);
			}
			return DictList;
		}

	}
}